#include "control/user_control.h"
#include "our_header.h"


int lsControl(int fd, MYSQL *conn, train_t *train) {

    extra_data_t *extra_data = (extra_data_t *)train->data;
    int cur_dir_id = extra_data->cur_dir_id;
    
    // 检查token是否匹配
    char token[4096] = {0};
    train_t response = {0};
    getToken(extra_data->user, token);
    if(strcmp(token,extra_data->token)){
        response.cmdstat = MKDIR|RES|!IS_OK;
        strcpy(response.data, "token验证失败\n");
        response.length = strlen(response.data)+1;
        send_train(fd, &response);
        return -1;
    }


    dir_list_t lists = {0};

    int ret = getDirList(conn, cur_dir_id, &lists);

    if(ret==0){
        
        response.cmdstat = LS | RES | IS_OK;
        memcpy(response.data, extra_data, sizeof(extra_data_t));
        memcpy(
               (char*)response.data + sizeof(extra_data_t), // 关键点：计算追加偏移量
               &lists.size,                               // 注意取地址符&
               sizeof(lists.size)
        );
        memcpy( (char*)response.data+sizeof(extra_data_t)+ sizeof(lists.size),lists.item_head,sizeof(dir_item_t)*lists.size);

        response.length=sizeof(cmdstat_t)+sizeof(int)+sizeof(extra_data_t)+sizeof(lists.size)+sizeof(dir_item_t)*lists.size;

    }else{
        response.cmdstat = LS | RES | !IS_OK;
        memcpy(response.data, extra_data, sizeof(extra_data_t));
        response.length = sizeof(extra_data_t);
    }
    send_train(fd, &response);
    if(lists.item_head) {
        free(lists.item_head);
    }
    return 0;
}


int pwdControl(int fd, MYSQL *conn, train_t *train) {

    extra_data_t *extra_data = (extra_data_t *)train->data;
    int cur_dir_id = extra_data->cur_dir_id;


    train_t response = {0};
    // 检查token是否匹配
    char token[4096] = {0};

    getToken(extra_data->user, token);
    if(strcmp(token,extra_data->token)){
        response.cmdstat = MKDIR|RES|!IS_OK;
        strcpy(response.data, "token验证失败\n");
        response.length = strlen(response.data)+1;
        send_train(fd, &response);
        return -1;
    }

    char path[1024] = {0};
    train_t data = {0};
    
    int ret = getPwd(conn, cur_dir_id, path);
    if(ret==0){
        response.cmdstat = PWD | RES | IS_OK;
        memcpy(response.data, extra_data, sizeof(extra_data_t));
        response.length = sizeof(extra_data_t) + 1; 
    }else{
        response.cmdstat = PWD | RES | !IS_OK;
        memcpy(response.data, extra_data, sizeof(extra_data_t));
        response.length = sizeof(extra_data_t)+1;
    }

    send_train(fd, &response);

    return 0;
}